package demo1;

import javax.xml.soap.Node;
import java.util.HashMap;
import java.util.Map;

public class Test {
    class Node{
        public int val;
        public Node next;
        public Node random;
        public Node(int val){
            this.val = val;
        }
    }
    public Node copyRandomList(Node head) {
        Node cur = head;
        Map<Node, Node> hashMap = new HashMap<>();
        /**
         *  先遍历一遍链表，并创建新链表给val赋值
         *  再给给hashMap分别赋值待被拷贝的链表结点地址和新创建的结点地址，使其对应起来
         */
        while(cur != null){
            Node node = new Node(cur.val);
            hashMap.put(cur, node);
            cur = cur.next;
        }
        //先让新链表连接起来,并把random赋给新结点
        cur = head;
        while(cur != null){
            hashMap.get(cur).next = hashMap.get(cur.next);
            hashMap.get(cur).random = hashMap.get(cur.random);
            cur = cur.next;
        }
        return hashMap.get(head);
    }
}
